package com.jiaotong.smart.smartjiaotong.service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiaotong.smart.smartjiaotong.entity.TimeSeriod;
import com.jiaotong.smart.smartjiaotong.mapper.TimeSeriodMapper;
import com.jiaotong.smart.smartjiaotong.structure.IntersectionStruct.*;

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;

import org.springframework.stereotype.Service;

@Service
public class IntersectionService {

    @Resource
    TimeSeriodMapper timeSeriodMapper;

    public IntersectionBaseInformationRes getIntersectionBaseInformation(IntersectionBaseInformationReq req) {
        IntersectionBaseInformationRes res = new IntersectionBaseInformationRes();
        // TODO 暂且留白，需要对齐协议

        return res;
    }

    public void setIntersectionPhasedLocked(IntersectionPhaseLockedReq req) {
        // TODO 留白，需要对齐
        return;
    }

    public void setIntersectionFlowDirection(IntersectionFlowDirectionReq req) {
        // TODO 留白，需要对齐
        return;
    }

    public boolean setIntersectionTimeSeriod(SetIntersectionTimeSeriodReq req) {
        // 筛选出启动的数值
        IntersectionTimeSeriod[] timeSeriods = Arrays.asList(req.getIntersectionTimeSeriods()).stream()
                .filter(timeSeriod -> timeSeriod.getWhetherStart() == 1).toArray(IntersectionTimeSeriod[]::new);
        // 根据开始时间排序，检查是否有重复的部门
        Arrays.sort(timeSeriods, new Comparator<IntersectionTimeSeriod>() {
            @Override
            public int compare(IntersectionTimeSeriod o1, IntersectionTimeSeriod o2) {
                return compareTime(o1.getStartTime(), o2.getStartTime());
            }
        });
        // 如果时间有重复的返回错误
        for (int i = 0; i < timeSeriods.length - 1; i++) {
            if (compareTime(timeSeriods[i].getEndTime(), timeSeriods[i + 1].getStartTime()) > 0) {
                return false;
            }
        }
        QueryWrapper<TimeSeriod> query = new QueryWrapper<>();
        // 删除原来所有该星期的数据
        timeSeriodMapper.delete(query.eq("week", req.getWeek()).eq("annunciator_id", req.getAnnunciatorID()));

        // 进行插入,考虑到插入顺序，不采用并发插入
        for (IntersectionTimeSeriod timeSeriod : req.getIntersectionTimeSeriods()) {
            timeSeriodMapper.insert(new TimeSeriod(timeSeriod.getStartTime(), timeSeriod.getEndTime(),
                    timeSeriod.getPhaseID(), timeSeriod.getControllMode(), timeSeriod.getWhetherStart(), req.getWeek(),
                    req.getAnnunciatorID()));
        }

        return true;
    }

    public GetIntersectionTimeSeriodRes getIntersectionTimeSeriods(GetIntersectionTimeSeriodReq req) {
        String week = req.getWeek();
        int annunciatorID = req.getAnnunciatorID();

        QueryWrapper<TimeSeriod> query = new QueryWrapper<>();
        // 查询出需要返回的数值
        List<TimeSeriod> timeSeriods = timeSeriodMapper
                .selectList(query.eq("week", week).eq("annunciator_id", annunciatorID));
        // 将实体类转换为返回的内容
        List<IntersectionTimeSeriod> intersectionTimeSeriods = Arrays
                .asList(timeSeriods.stream().map(new Function<TimeSeriod, IntersectionTimeSeriod>() {
                    @Override
                    public IntersectionTimeSeriod apply(TimeSeriod t) {
                        return new IntersectionTimeSeriod(t.getWhetherStart(), t.getStartTime(), t.getEndTime(),
                                t.getPhaseSheme(), t.getControlMode());
                    }
                }).toArray(IntersectionTimeSeriod[]::new));
        return new GetIntersectionTimeSeriodRes(intersectionTimeSeriods);
    }

    // 对比时间长度
    private int compareTime(String time1, String time2) {
        DateFormat df = new SimpleDateFormat("HH:mm");
        try {
            int res = df.parse(time1).compareTo(df.parse(time2));
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}
